package org.kumas.sgrpc.rpc.protocol.injvm;

import java.util.Map;

import org.kumas.sgrpc.common.URL;
import org.kumas.sgrpc.rpc.Constants;
import org.kumas.sgrpc.rpc.Exporter;
import org.kumas.sgrpc.rpc.Invocation;
import org.kumas.sgrpc.rpc.Invoker;
import org.kumas.sgrpc.rpc.Result;
import org.kumas.sgrpc.rpc.RpcContext;
import org.kumas.sgrpc.rpc.RpcException;
import org.kumas.sgrpc.rpc.protocol.AbstractInvoker;

import static org.kumas.sgrpc.common.constants.CommonConstants.LOCALHOST_VALUE;

/**
 * @author KumasZhang
 * @version 1.0
 * @since 2021-07-27 12:06
 */
public class InjvmInvoker<T> extends AbstractInvoker<T> {
    private final String key;

    private final Map<String, Exporter<?>> exporterMap;

    InjvmInvoker(Class<T> type, URL url, String key, Map<String, Exporter<?>> exporterMap) {
        super(type, url);
        this.key = key;
        this.exporterMap = exporterMap;
    }

    @Override
    public boolean isAvailable() {
        InjvmExporter<?> exporter = (InjvmExporter<?>) exporterMap.get(key);
        if (exporter == null) {
            return false;
        } else {
            return super.isAvailable();
        }
    }

    @Override
    public Result doInvoke(Invocation invocation) throws Throwable {
        Exporter<?> exporter = InjvmProtocol.getExporter(exporterMap, getUrl());
        if (exporter == null) {
            throw new RpcException("Service [" + key + "] not found.");
        }

        RpcContext.getContext().setRemoteAddress(LOCALHOST_VALUE, 0);
        // Solve local exposure, the server opens the token, and the client call fails.
        URL serverURL = exporter.getInvoker().getUrl();
        boolean serverHasToken = serverURL.hasParameter(Constants.TOKEN_KEY);

        if (serverHasToken) {
            invocation.setAttachment(Constants.TOKEN_KEY, serverURL.getParameter(Constants.TOKEN_KEY));
        }
        return exporter.getInvoker().invoke(invocation);
    }
}
